#include "dkglLight.h"
#include <sstream>
#include <string>

namespace DKGL
{

using namespace std;

void Light::_initParam()
{
	float pos[] = {0.0f, 0.0f, 0.0f, 1.0f};
	
	//glEnable(GL_LIGHT0 + mID);
	for(int i=0;i<3;i++)
		mAmbient[i] = mDiffuse[i] = mSpecular[i] = 1.0f;

	glLightfv(GL_LIGHT0 + mID, GL_AMBIENT, mAmbient);
	glLightfv(GL_LIGHT0 + mID, GL_DIFFUSE, mDiffuse);
	glLightfv(GL_LIGHT0 + mID, GL_SPECULAR, mSpecular);
	glLightfv(GL_LIGHT0 + mID, GL_POSITION, pos);
}

Light& Light::enable(bool b)
{
	mBeEnable = b;
	mBeEnable? glEnable(GL_LIGHT0 + mID): glDisable(GL_LIGHT0 + mID);
	return *this;
}

Light& Light::setAmbient(const Colorf& amb)
{
	mAmbient[0] = amb.r;
	mAmbient[1] = amb.g;
	mAmbient[2] = amb.b;
	mAmbient[3] = amb.a;

	glLightfv(GL_LIGHT0 + mID, GL_AMBIENT, mAmbient);
	return *this;
}

Light& Light::setDiffuse(const Colorf& color)
{
	mDiffuse[0] = color.r;
	mDiffuse[1] = color.g;
	mDiffuse[2] = color.b;
	mDiffuse[3] = color.a;

	glLightfv(GL_LIGHT0 + mID, GL_DIFFUSE, mDiffuse);
	return *this;
}

Light& Light::setSpecular(const Colorf& color)
{
	mSpecular[0] = color.r;
	mSpecular[1] = color.g;
	mSpecular[2] = color.b;
	mSpecular[3] = color.a;

	glLightfv(GL_LIGHT0 + mID, GL_SPECULAR, mSpecular);
	return *this;
}

void Light::render()
{
	float globalMatrix[16];
	glGetFloatv( GL_MODELVIEW_MATRIX , globalMatrix );
	_transformation();

	glLightfv(GL_LIGHT0 + mID, GL_POSITION, &mLocalMatrix[12]);
	
	//if(mNeedCalculateNormal) // check if need to re-calculate normal
	//	_calculateNormal();
	
	if(mShow) // draw itself
	{
		//glPushAttrib(GL_LIGHTING_BIT);
		//mEnableLighting ? glEnable(GL_LIGHTING) : glDisable(GL_LIGHTING);
		//mEnableColorTracking ? glEnable(GL_COLOR_MATERIAL) : glDisable(GL_COLOR_MATERIAL);
		drawEntity();
		//glPopAttrib();
	}
	_renderChildren(); // render the children if necessary
	
	glLoadMatrixf(globalMatrix);
}
	
void Light::drawEntity()
{
	//glLightfv(mID, GL_POSITION, &mLocalMatrix[12]);

	glPushAttrib(GL_LIGHTING_BIT | GL_POLYGON_BIT);
	glDisable(GL_LIGHTING);
	glPolygonMode(GL_FRONT, GL_FILL);
	GLUquadricObj *quadratic;
	//glPushMatrix();
	glColor3ub(0xFF, 0xFF, 0xFF);
	quadratic = gluNewQuadric();

	//glTranslatef(mPosition.x, mPosition.y, mPosition.z);
	gluSphere(quadratic,1.3f,8,8);	
	gluDeleteQuadric(quadratic);
	//glPopMatrix();
	glPopAttrib();
}

void LightManager::_initLightID(void)
{
	for(int i=0;i<8;i++)
	{
		ostringstream ss;		
		ss << i;
		mLight[i].mID = i;
		mLight[i]._initParam();
		mLight[i].setName(string("Light") + ss.str());
	}
}

}